package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.player.WorldMessageMgr;
import com.yanqu.road.server.manager.union.CrossUnionReqContext;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.List;

@Cmd(code = Protocol.C_UNION_MEMBER_CHAT_LIST, desc = "商会聊天列表")
public class CrossUnionMemberChatListCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        CrossUnionReqContext context = CrossUnionReqContext.initContext(serverId, packet.getPlayerId()).loadUnionMember().loadUnionInfo();
        if(context.getRet() != 0){
            return;
        }

        CrossUnionProto.UnionMemberChatListCrossUploadMsg uploadMsg = CrossUnionProto.UnionMemberChatListCrossUploadMsg.parseFrom(packet.getBytes());
        List<WorldMessageProto.WorldMessageTempMsg.Builder> unionMessageList = WorldMessageMgr.getUnionMessageMsgList(context.getUnionInfo().getUnionUid());
        if(null != unionMessageList) {
            for (WorldMessageProto.WorldMessageTempMsg tempMsg : uploadMsg.getMsgListList()) {
                unionMessageList.add(tempMsg.toBuilder());
            }
            unionMessageList.sort((o1, o2) -> (int) (o1.getSendTime() - o2.getSendTime()));
            while (unionMessageList.size() > WorldMessageMgr.MAX_MESSAGE_COUNT) {
                unionMessageList.remove(0);
            }
            WorldMessageProto.WorldMessageListMsg.Builder messageList = WorldMessageProto.WorldMessageListMsg.newBuilder();
            for (WorldMessageProto.WorldMessageTempMsg.Builder builder : unionMessageList) {
                messageList.addDataList(builder);
            }
            MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_WORLD_MESSAGE_LIST, messageList));
		}

    }

    @Override
    public void sendData() {

    }
}
